<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/login.css">   
    
    <!--IMPORTANT:Bind data from server to javascript variables-->
    <script type="text/javascript">  
        var _appKeys=<%- JSON.stringify(appKeys) %>;       
        var _generalSettings=<%- JSON.stringify(generalSettings) %>; 
        var _authSettings=<%- JSON.stringify(authSettings) %>;       
    </script>  

</head>
<body>

<div class="wrapper">
    <div class="container">
    <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12">

    <div class="flex-general-column-wrapper-center" style="height: 99vh;position: relative;">

        <!--Login or Sing Up form-->
        <div id="authenticate-card" class="" style=" width:340px;">
            <div class="" style="height:auto;border-radius:2px; border:1px solid #BAB8B8;">
                <!--Header-->
                <div style="width:100%;height:117px;background-color:#dddddd;padding:15px;">                 

                    <div style="width:100%;" class="flex-general-column-wrapper-center">
                        <% if (generalSettings && generalSettings.appIcon) { %>
                            <div style="width:50px;height:50px;border-radius: 10px;overflow: hidden;">
                                <img src="<%= generalSettings.appIcon %>" style="width:50px;height:50px;">
                            </div>
                        <%}else{%>
                            <div style="width:50px;height:50px;border-radius: 10px;overflow: hidden;">
                                <img src="assets/images/CbLogoIcon.png" style="width:50px;height:50px;">
                            </div>
                        <%}%>    
                    </div>

                    <div style="width:100%;margin-top: -5px;" class="flex-general-column-wrapper-center">
                        <% if (generalSettings && generalSettings.appName) { %>
                            <h3><%= generalSettings.appName %></h3>
                        <%}else{%>
                            <h3>App on CloudBoost</h3>
                        <%}%>    
                    </div>

                </div>
                <!--Header-->

                <!--Main Body Spinner-->
                <div id="authenticate-spinner" style="width: 100%;height: 200px;background-color: white;" class="flex-general-column-wrapper-center">
                    <div style="width: 60px;height: 60px;" class="flex-general-column-wrapper-center">
                        <div style="" class="loader-circle advanced flex-general-column-wrapper-center">                        
                        </div>                        
                    </div>
                </div>
                <!--Main Body Spinner-->

                <center>
                    <div id="page-not-found-message" class="solo-horizontal-center" style="background-color: white;padding: 10px;">
                
                        <!--Info-->
                        <div style="width: 100%;margin-top: 20px;" class="solo-horizontal-center">
                            <div style="width: 100%;margin-top: 20px;margin-bottom: 20px;" class="solo-horizontal-center">
                                <p style="color:gray">
                                    Oops, page not found.
                                </p>
                            </div>
                        </div>
                    </div>
                </center>

                <center>
                    <div id="success-message" class="solo-horizontal-center" style="background-color: white;padding: 10px;">       
                        <!--Info-->
                        <div style="width: 100%;margin-top: 20px;" class="solo-horizontal-center">
                            <div style="width: 100%;margin-top: 20px;margin-bottom: 20px;" class="solo-horizontal-center">
                                <p style="color:gray">
                                    Your password has been changed successfully.
                                    <br/><br/>
                                    <a id="login-link" class="loginButton">Login</a>
                                </p>
                            </div>
                        </div>
                    </div>
                </center>
                <center>
                    <div id="success-message-redirect" class="solo-horizontal-center" style="background-color: white;padding: 10px;">              
                        <!--Info-->
                        <div style="width: 100%;margin-top: 20px;" class="solo-horizontal-center">
                            <div style="width: 100%;margin-top: 20px;margin-bottom: 20px;" class="solo-horizontal-center">
                                <p style="color:gray">
                                    Your password has been changed successfully.
                                    <br/><br/>
                                </p>
                            </div>
                        </div>
                    </div>
                </center>

                <!--Main Body Content-->
                <div id="authenticate-mainbody" style="">
                    <!--Error Block-->
                    <div id="authenticate-error" style="background-color: #f04848;padding: 10px;" class="solo-horizontal-center">
                        <span style="color:white;">Unknown Error</span>
                    </div>
                    <!--Error Block-->

                    <!--Body-->
                    <div style="background-color: white;padding-top: 5px;">
                        
                        <div style="background-color: white;padding-bottom: 24px;padding-left: 20px;padding-right: 20px;">                           

                            <% if(!authSettings || (authSettings && authSettings.custom.enabled)){ %>
                            <!--Login Input Fields-->                        
                            <div id="login-inputfields" style="width: 100%;margin-top: 8px;" class="solo-horizontal-center">
                             <!--Info-->
                                <div style="width: 100%;margin-top: 20px;" class="solo-horizontal-center">
                                    <p style="color:gray">
                                    Change your password.
                                    </p>
                                </div>                                        
                                <div style="width: 95%;">
                                    <div id="new-password-wrap" class="flex-general-row-wrapper input-field" style="">
                                        <div class="flex-general-column-wrapper-center" style="width:13%; height: 35px;background-color:#f1f1f1;">
                                            <i class="icon ion-ios-locked-outline" style="color:gray;font-size: 22px;"></i>
                                        </div>
                                        <div style="width:86.98%; height: 35px;">
                                            <input id="new-password" type="password" placeholder="New Password" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">
                                        </div>
                                    </div>

                                    <div id="confirm-password-wrap" class="flex-general-row-wrapper input-field" style="">
                                        <div class="flex-general-column-wrapper-center" style="width:13%; height: 35px;background-color:#f1f1f1;">
                                            <i class="icon ion-ios-locked-outline" style="color:gray;font-size: 22px;"></i>
                                        </div>
                                        <div style="width:86.98%; height: 35px;">
                                            <input id="confirm-password" type="password" placeholder="Confrim Password" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">
                                        </div>
                                    </div>
                                </div>                                        
                            </div>
                            <%}%>
                            <!--/Login Input Fields-->

                            <% if(authSettings && !authSettings.custom.enabled){ %>
                            <!--Custom Auth is disabled-->                        
                            <!--Body-->
                            <div style="background-color: white;padding: 10px;">
                        
                                <!--Info-->
                                <div style="width: 100%;margin-top: 20px;" class="solo-horizontal-center">
                                    <p style="color:gray">
                                    Custom Authentication is disbaled for this app. Please enable custom authentiation in your App Settings on CloudBoost Dashboard to enable this feature.
                                    </p>
                                </div>
                            </div>
                            <!--Body-->
                            <%}%>

                            
                            
                             
                        
                        </div>    
                    </div>
                    <!--Body-->

                    <% if(!authSettings || (authSettings && authSettings.custom.enabled)){ %>
                    <!--Button-->
                    <div class="final-btn" style="">
                       <div style="width: 100%;height: 30px;" class="flex-general-column-wrapper-center">
                            <span style="color:white;font-size: 34px;">
                                <i class="icon ion-log-in"></i>
                            </span>
                       </div>
                    </div>
                    <!--Button-->
                    <%}%>



                </div>
                <!--/Main Body Content-->
            </div>
        </div>
        <!--/Login or Sing Up form-->



        <div class="flex-general-column-wrapper-center" style="width: 100%;height: 60px;margin-top: 1.5%;">
            <div class="flex-general-row-wrapper">
                <p style="color:#aeb3ba;">powered by</p>
                <p style="color:#aeb3ba;">&nbsp;<a style="color:#aeb3ba;" href="https://www.cloudboost.io">CloudBoost</a></p>
            </div>
        </div>
    </div>     

</div>
</div>
</div>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cloudboost.io/js-sdk/cloudboost.js"></script>

<script>  
    var serverURL="https://cloudboost.i/api/";  
    var __isDevelopment = false;

    if(window.location.host.indexOf('localhost') > -1){
        __isDevelopment = true;
        var serverURL="http://localhost:4730"; 
    }



    //This is the fucntion to get querysting, 
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function _emailValidation(email){
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

        if (!filter.test(email)) {            
            return false;
        }

        return true;
    }

    function LightenDarkenColor(col, amt) {
      
        var usePound = false;
      
        if (col[0] == "#") {
            col = col.slice(1);
            usePound = true;
        }
     
        var num = parseInt(col,16);
     
        var r = (num >> 16) + amt;
     
        if (r > 255) r = 255;
        else if  (r < 0) r = 0;
     
        var b = ((num >> 8) & 0x00FF) + amt;
     
        if (b > 255) b = 255;
        else if  (b < 0) b = 0;
     
        var g = (num & 0x0000FF) + amt;
     
        if (g > 255) g = 255;
        else if (g < 0) g = 0;
     
        return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
      
    }

    //Remove #_=_' from URL
    if (window.location.hash == '#_=_'){

        // Check if the browser supports history.replaceState.
        if (history.replaceState) {

            // Keep the exact URL up to the hash.
            var cleanHref = window.location.href.split('#')[0];

            // Replace the URL in the address bar without messing with the back button.
            history.replaceState(null, null, cleanHref);

        } else {

            // Well, you're on an old browser, we can get rid of the _=_ but not the #.
            window.location.hash = '';

        }

    }

    
    $(document).ready(function(){         

        //Init CloudBoost
        CB.CloudApp.init(serverURL, _appKeys.appId, _appKeys.masterKey);      

        $("#authenticate-error").hide();
        $("#authenticate-spinner").hide();
        $("#success-message").hide();
        $("#success-message-redirect").hide();
        
        if(getParameterByName('resetKey') && getParameterByName('resetKey'))
        {
        
            $("#page-not-found-message").hide();
            $(".login-btn").addClass("btn-active");
            if(_authSettings && _authSettings.general &&  _authSettings.general.primaryColor){
                $(".final-btn").css({"background-color": _authSettings.general.primaryColor}); 
                $(".resetpwd-final-btn").css({"background-color": _authSettings.general.primaryColor});
            }
        }else{
             $("#authenticate-error span").text("");
             $("#authenticate-error").hide(); 
             $("#authenticate-mainbody").hide();
             $("#page-not-found-message").show();
        }
      
    });

    $(".final-btn").hover(function(){
        $(this).css("background-color", LightenDarkenColor(_authSettings.general.primaryColor,-40));
    }, function(){
        $(this).css("background-color", _authSettings.general.primaryColor);
    });


    $(".final-btn").click(function(){ 
        
        $("#authenticate-error span").text("");
        $("#authenticate-error").hide();       

        //Login
        
        $("#new-password-wrap").removeClass("input-field-error");
        $("#confirm-password-wrap").removeClass("input-field-error");

        var newPassword=$("#new-password").val();
        var confirmPassword=$("#confirm-password").val();

        var validationsPassed=true;

        if(!newPassword){
            $("#new-password-wrap").addClass("input-field-error");
            validationsPassed=false;                
        }            

        if(!confirmPassword){
            $("#confirm-password-wrap").addClass("input-field-error");
            validationsPassed=false;                
        }

        if(newPassword === confirmPassword){

            if(validationsPassed){
                //Submit form

                
                $("#authenticate-mainbody").hide();
                $("#authenticate-spinner").show();

                $.ajax({
                    url: window.location.origin+"/page/"+window.location.pathname.split('/')[2]+"/reset-user-password",
                
                    // The data to send (will be converted to a query string)
                    data: {
                        resetKey : getParameterByName('resetKey'),
                        username : getParameterByName('user'),
                        newPassword : newPassword
                    },
                    
                    // Whether this is a POST or GET request
                    type: "POST",
                    
                    // The type of data we expect back
                    dataType : "json",
                    
                    // Code to run if the request succeeds;
                    // the response is passed to the function
                    success: function( json ) {
                       //Success :) Have Login button.
                       $("#authenticate-spinner").hide();
                       if (_authSettings.resetPasswordEmail.redirectURL.enabled===true) {                      
                        if (!_authSettings.resetPasswordEmail.redirectURL.URL) {
                            throwAuthError("Please add your app's password reset redirect URL in your CloudBoost App Settings.");
                        } else {
                            $("#success-message-redirect").show();
                            setTimeout("location.href = _authSettings.resetPasswordEmail.redirectURL.URL;",2000);
                        }
                       } else {
                        $("#login-link").attr("href", window.location.origin+"/page/"+window.location.pathname.split('/')[2]+"/authentication");
                        $("#success-message").show();
                       }
                    },                    
                    // Code to run if the request fails; the raw request and
                    // status codes are passed to the function
                    error: function( xhr, status, errorThrown ) {
                        throwAuthError(JSON.parse(xhr.responseText).error);
                        return;
                    }
                });
            }
        }
        else{
            throwAuthError("New Password and Confirm Password do not match.");
        }
        
    });


    $(".resetpwd-final-btn").click(function(){ 
        
        $("#forgetpassword-error span").text("");
        $("#forgetpassword-error").hide();
        $("#req-response").text("");
        $("#req-spinner").show();
        $("#goback-btn").show();
        

        $("#forgot-email-wrap").removeClass("input-field-error");        

        var email=$("#forgot-email").val();        
        var validationsPassed=true;

        if(!email){
            $("#forgot-email-wrap").addClass("input-field-error");
            validationsPassed=false;                
        } 

        if(email && !_emailValidation(email)){
            $("#forgot-email-wrap").addClass("input-field-error"); 
            validationsPassed=false;               
        }        

        if(validationsPassed){
            //Submit form

            $("#forgetpassword-mainbody").hide();
            $("#forgetpassword-spinner").show();
             $("#goback-btn").hide();

            CB.CloudUser.resetPassword(email,{
              success: function(response) {
                $("#req-spinner").hide();
                $("#req-response").text("Success");
                $("#goback-btn").show();                
              },
              error: function(error) {
                $("#goback-btn").show();
                try{
                    error=JSON.parse(error);
                }catch(e){}

                if(error && error.error){
                    throwForgotError(error.error);
                }else if(error && error.message){
                    throwForgotError(error.message);
                }else{  
                    throwForgotError("Something went wrong..");                   
                }
              }
            });
        }
    });

    function throwAuthError(error){
        $("#authenticate-spinner").hide();
        $("#authenticate-mainbody").show();

        $("#authenticate-error").show();
        $("#authenticate-error span").text(error);
    }

    function throwForgotError(error){
        $("#forgetpassword-spinner").hide();
        $("#forgetpassword-mainbody").show();

        $("#forgetpassword-error").show();
        $("#forgetpassword-error span").text(error);
    }      

</script>

<script type="text/javascript">
    $("#facebook-login-btn").click(function(){
        if(checkCallBackUrl()){
            var url=serverURL+"/auth/"+_appKeys.appId+"/facebook";
            requestLoginUrl(url);
        }
                
    });

    $("#twittr-login-btn").click(function(){
        if(checkCallBackUrl()){
            var url=serverURL+"/auth/"+_appKeys.appId+"/twitter";
            requestLoginUrl(url);    
        }    
    });

    $("#github-login-btn").click(function(){
        if(checkCallBackUrl()){
            var url=serverURL+"/auth/"+_appKeys.appId+"/github";
            requestLoginUrl(url); 
        }     
    });

    $("#google-login-btn").click(function(){
        if(checkCallBackUrl()){
            var url=serverURL+"/auth/"+_appKeys.appId+"/google";
            requestLoginUrl(url);  
        }     
    });

    $("#linkedin-login-btn").click(function(){
        if(checkCallBackUrl()){
            var url=serverURL+"/auth/"+_appKeys.appId+"/linkedin";
            requestLoginUrl(url);  
        }     
    });    

    function requestLoginUrl(url){
        $.get(url, function(data, status){            
            if(data && data.url){
                var loginUrl=data.url;
                window.open(loginUrl,"_self");
            }           
       });
    }

    function checkCallBackUrl() {
        if(!_authSettings || !_authSettings.general.callbackURL){
            throwAuthError("Please add your app callback URL in your CloudBoost App Settings.");
            return false;
        }
        return true;
    }
</script>

</html>



